<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="Maven依赖12345678910&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;&#x2F;artifactId&gt;&lt;&#x2F;dependency&gt;&lt;!-- lettuce">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot集成Redis ———— 序列化配置、常见工具类、基本的CRUD">
<meta property="og:url" content="http://example.com/2021/09/28/SpringBoot%E9%9B%86%E6%88%90Redis-%E2%80%94%E2%80%94%E2%80%94%E2%80%94-%E5%BA%8F%E5%88%97%E5%8C%96%E9%85%8D%E7%BD%AE%E3%80%81%E5%B8%B8%E8%A7%81%E5%B7%A5%E5%85%B7%E7%B1%BB%E3%80%81%E5%9F%BA%E6%9C%AC%E7%9A%84CRUD/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="Maven依赖12345678910&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;&#x2F;artifactId&gt;&lt;&#x2F;dependency&gt;&lt;!-- lettuce">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-27T16:00:00.000Z">
<meta property="article:modified_time" content="2021-10-24T06:26:47.421Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="NoSQL">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="SpringBoot 集成一切">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/09/28/SpringBoot%E9%9B%86%E6%88%90Redis-%E2%80%94%E2%80%94%E2%80%94%E2%80%94-%E5%BA%8F%E5%88%97%E5%8C%96%E9%85%8D%E7%BD%AE%E3%80%81%E5%B8%B8%E8%A7%81%E5%B7%A5%E5%85%B7%E7%B1%BB%E3%80%81%E5%9F%BA%E6%9C%AC%E7%9A%84CRUD/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/09/28/SpringBoot%E9%9B%86%E6%88%90Redis-%E2%80%94%E2%80%94%E2%80%94%E2%80%94-%E5%BA%8F%E5%88%97%E5%8C%96%E9%85%8D%E7%BD%AE%E3%80%81%E5%B8%B8%E8%A7%81%E5%B7%A5%E5%85%B7%E7%B1%BB%E3%80%81%E5%9F%BA%E6%9C%AC%E7%9A%84CRUD/","path":"2021/09/28/SpringBoot集成Redis-————-序列化配置、常见工具类、基本的CRUD/","title":"SpringBoot集成Redis ———— 序列化配置、常见工具类、基本的CRUD"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>SpringBoot集成Redis ———— 序列化配置、常见工具类、基本的CRUD | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Maven%E4%BE%9D%E8%B5%96"><span class="nav-number">1.</span> <span class="nav-text">Maven依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-%E8%BF%9E%E6%8E%A5-redis-%E7%9A%84%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="nav-number">2.</span> <span class="nav-text">Java 连接 redis 的客户端</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BA%8F%E5%88%97%E5%8C%96%E9%85%8D%E7%BD%AE"><span class="nav-number">3.</span> <span class="nav-text">序列化配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#yml%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE"><span class="nav-number">4.</span> <span class="nav-text">yml基本配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="nav-number">5.</span> <span class="nav-text">工具类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Json%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="nav-number">5.1.</span> <span class="nav-text">Json工具类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%8D%95Bean%E7%B1%BB%E4%B8%8EMap%E4%B9%8B%E9%97%B4%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="nav-number">5.2.</span> <span class="nav-text">简单Bean类与Map之间的转换</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CRUD"><span class="nav-number">6.</span> <span class="nav-text">CRUD</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84Entity"><span class="nav-number">6.1.</span> <span class="nav-text">简单的Entity</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95-String"><span class="nav-number">6.2.</span> <span class="nav-text">测试 String</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95-Hash"><span class="nav-number">6.3.</span> <span class="nav-text">测试 Hash</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95-Json%E5%BA%8F%E5%88%97%E5%8C%96"><span class="nav-number">6.4.</span> <span class="nav-text">测试 Json序列化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95-HyperLogLog"><span class="nav-number">6.5.</span> <span class="nav-text">测试 HyperLogLog</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95-BitMap"><span class="nav-number">6.6.</span> <span class="nav-text">测试 BitMap</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95-Lua"><span class="nav-number">6.7.</span> <span class="nav-text">测试 Lua</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/28/SpringBoot%E9%9B%86%E6%88%90Redis-%E2%80%94%E2%80%94%E2%80%94%E2%80%94-%E5%BA%8F%E5%88%97%E5%8C%96%E9%85%8D%E7%BD%AE%E3%80%81%E5%B8%B8%E8%A7%81%E5%B7%A5%E5%85%B7%E7%B1%BB%E3%80%81%E5%9F%BA%E6%9C%AC%E7%9A%84CRUD/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="SpringBoot集成Redis ———— 序列化配置、常见工具类、基本的CRUD | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          SpringBoot集成Redis ———— 序列化配置、常见工具类、基本的CRUD
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-09-28 00:00:00" itemprop="dateCreated datePublished" datetime="2021-09-28T00:00:00+08:00">2021-09-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-10-24 14:26:47" itemprop="dateModified" datetime="2021-10-24T14:26:47+08:00">2021-10-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Redis/" itemprop="url" rel="index"><span itemprop="name">Redis</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="Maven依赖"><a href="#Maven依赖" class="headerlink" title="Maven依赖"></a>Maven依赖</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- lettuce连接池需要依赖下面的jar包 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.commons<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-pool2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p>序列化依赖，如果使用 spring-boot-starter-web, 就不需要了。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-json<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h2 id="Java-连接-redis-的客户端"><a href="#Java-连接-redis-的客户端" class="headerlink" title="Java 连接 redis 的客户端"></a>Java 连接 redis 的客户端</h2><blockquote>
<p>操作redis的客户端有jedis跟Lettuce。在springboot1.x系列中，其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce。 因为我们的版本是springboot2.x系列，所以今天使用的是Lettuce。<br>关于jedis跟lettuce的区别：</p>
<ul>
<li>Lettuce 和 Jedis 的定位都是Redis的client，所以他们当然可以直接连接redis server  </li>
<li>Jedis在实现上是直接连接的redis server，如果在多线程环境下是非线程安全的，这个时候只有使用连接池，为每个Jedis实例增加物理连接;</li>
<li>Lettuce的连接是基于Netty的，连接实例（StatefulRedisConnection）可以在多个线程间并发访问，应为StatefulRedisConnection是线程安全的，所以一个连接实例（StatefulRedisConnection）就可以满足多线程环境下的并发访问，当然这个也是可伸缩的设计，一个连接实例不够的情况也可以按需增加连接实例。</li>
</ul>
</blockquote>
<h2 id="序列化配置"><a href="#序列化配置" class="headerlink" title="序列化配置"></a>序列化配置</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RedisConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> RedisTemplate <span class="title function_">redisTemplate</span><span class="params">(RedisConnectionFactory connectionFactory)</span> &#123;</span><br><span class="line">        <span class="type">RedisTemplate</span> <span class="variable">redisTemplate</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RedisTemplate</span>();</span><br><span class="line">        <span class="comment">// 设置template获得 redis-connection 的工厂</span></span><br><span class="line">        redisTemplate.setConnectionFactory(connectionFactory);</span><br><span class="line">        <span class="comment">// 设置序列化器</span></span><br><span class="line">        redisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);</span><br><span class="line">        redisTemplate.setValueSerializer(RedisSerializer.json()); <span class="comment">// value 序列化器使用 Json</span></span><br><span class="line">        redisTemplate.setHashKeySerializer(StringRedisSerializer.UTF_8);</span><br><span class="line">        redisTemplate.setHashValueSerializer(StringRedisSerializer.UTF_8);</span><br><span class="line">        <span class="keyword">return</span> redisTemplate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="yml基本配置"><a href="#yml基本配置" class="headerlink" title="yml基本配置"></a>yml基本配置</h2><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">redis:</span></span><br><span class="line">    <span class="attr">database:</span> <span class="number">0</span> <span class="comment">#使用第几个数据库</span></span><br><span class="line">    <span class="attr">host:</span> <span class="string">localhost</span> <span class="comment">#redis服务器地址</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">6379</span> <span class="comment">#端口号</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">~</span> <span class="comment">#redis服务器连接密码</span></span><br><span class="line">    <span class="attr">timeout:</span> <span class="number">10000</span>  <span class="comment"># 连接超时时间（单位：毫秒）</span></span><br><span class="line">    <span class="attr">lettuce:</span></span><br><span class="line">      <span class="attr">pool:</span></span><br><span class="line">        <span class="comment">## 下面的值其实是lettuce连接池的默认配置，有兴趣的可以点进源码看一下</span></span><br><span class="line">        <span class="attr">max-active:</span> <span class="number">8</span> <span class="comment">#连接池最大连接数（使用负值表示没有限制）</span></span><br><span class="line">        <span class="attr">max-wait:</span> <span class="number">-1</span>  <span class="comment">#连接池最大阻塞等待时间（单位：使用负值表示没有限制）</span></span><br><span class="line">        <span class="attr">max-idle:</span> <span class="number">8</span> <span class="comment">#连接池中的最大空闲连接</span></span><br><span class="line">        <span class="attr">min-idle:</span> <span class="number">0</span> <span class="comment">#连接池中的最小空闲连接</span></span><br></pre></td></tr></table></figure>



<h2 id="工具类"><a href="#工具类" class="headerlink" title="工具类"></a>工具类</h2><h3 id="Json工具类"><a href="#Json工具类" class="headerlink" title="Json工具类"></a>Json工具类</h3><p>主要是将检查型异常改为运行时异常抛出</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Json工具类, 功能为对象和字符串互相转换</span></span><br><span class="line"><span class="comment"> * 注意，jackson的属性注入是 无参构造器+getter+setter</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">JsonUtil</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">ObjectMapper</span> <span class="variable">mapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Serialize any Java value as a String.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">stringfy</span><span class="params">(Object object)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> mapper.writeValueAsString(object);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JsonProcessingException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;JsonUtil stringfy error: &quot;</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Deserialize JSON content from given JSON content String.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; T <span class="title function_">parse</span><span class="params">(String content, Class&lt;T&gt; valueType)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> mapper.readValue(content, valueType);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JsonProcessingException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;JsonUtil parse error: &quot;</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="简单Bean类与Map之间的转换"><a href="#简单Bean类与Map之间的转换" class="headerlink" title="简单Bean类与Map之间的转换"></a>简单Bean类与Map之间的转换</h3><p>这个工具类的转换，主要是在使用 redis 的 hash 结构去存储实体类的时候使用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: SongyangJi</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 提供简单bean类与map之间的转化</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span>: 2021/9/16</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">BeanAndMapConvertUtil</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Map&lt;String, Object&gt; <span class="title function_">beanToMap</span><span class="params">(Object object)</span> &#123;</span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, Object&gt;();</span><br><span class="line">        <span class="keyword">for</span> (Field field : object.getClass().getDeclaredFields()) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> field.isAccessible();</span><br><span class="line">                field.setAccessible(<span class="literal">true</span>);</span><br><span class="line">                <span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> field.get(object);</span><br><span class="line">                map.put(field.getName(), obj != <span class="literal">null</span> ? obj.toString() : <span class="string">&quot;&quot;</span>);</span><br><span class="line">                field.setAccessible(flag);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e.getMessage());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; T <span class="title function_">mapToBean</span><span class="params">(Map&lt;String, Object&gt; map, Class&lt;T&gt; beanClass)</span> &#123;</span><br><span class="line">        T t;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            t = beanClass.newInstance();</span><br><span class="line">            <span class="keyword">for</span> (Field field : beanClass.getDeclaredFields()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (map.containsKey(field.getName())) &#123;</span><br><span class="line">                    <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> field.isAccessible();</span><br><span class="line">                    field.setAccessible(<span class="literal">true</span>);</span><br><span class="line">                    <span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> map.get(field.getName());</span><br><span class="line">                    <span class="keyword">if</span> (obj != <span class="literal">null</span>) &#123;</span><br><span class="line">                        <span class="keyword">if</span> (field.getType().isAssignableFrom(obj.getClass())) &#123;</span><br><span class="line">                            field.set(t, obj);</span><br><span class="line">                        &#125;</span><br><span class="line">                        field.setAccessible(flag);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> t;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>





<h2 id="CRUD"><a href="#CRUD" class="headerlink" title="CRUD"></a>CRUD</h2><h3 id="简单的Entity"><a href="#简单的Entity" class="headerlink" title="简单的Entity"></a>简单的Entity</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="type">long</span> userId;</span><br><span class="line"></span><br><span class="line">    String name;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> age;</span><br><span class="line"></span><br><span class="line">    <span class="type">double</span> weight;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> score;</span><br><span class="line"></span><br><span class="line">    LocalDate lastSignDay;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="测试-String"><a href="#测试-String" class="headerlink" title="测试 String"></a>测试 String</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">testString</span><span class="params">()</span> &#123;</span><br><span class="line">      redisTemplate.opsForValue().set(<span class="string">&quot;str_key&quot;</span>, <span class="string">&quot;hello_world&quot;</span>);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>





<h3 id="测试-Hash"><a href="#测试-Hash" class="headerlink" title="测试 Hash"></a>测试 Hash</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">testBeanAndHash</span><span class="params">()</span> &#123;</span><br><span class="line">      <span class="type">User</span> <span class="variable">songyangJi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">12345L</span>, <span class="string">&quot;SongyangJi&quot;</span>, <span class="number">18</span>, <span class="number">73.5</span>, <span class="number">0</span>, <span class="literal">null</span>);</span><br><span class="line">      <span class="keyword">final</span> <span class="type">String</span> <span class="variable">user_hash_key</span> <span class="operator">=</span> <span class="string">&quot;user_hash&quot;</span>;</span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">&quot;------ 使用 Hash 存储对象 ------&quot;</span>);</span><br><span class="line">      <span class="comment">// 使用Hash结构，map传入</span></span><br><span class="line">      redisTemplate.opsForHash().putAll(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId(), BeanAndMapConvertUtil.beanToMap(songyangJi));</span><br><span class="line"></span><br><span class="line">      <span class="type">BoundHashOperations</span> <span class="variable">hashOs</span> <span class="operator">=</span> redisTemplate.boundHashOps(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId());</span><br><span class="line">      System.out.println(hashOs.get(<span class="string">&quot;userId&quot;</span>));</span><br><span class="line">      System.out.println(hashOs.get(<span class="string">&quot;name&quot;</span>));</span><br><span class="line">      hashOs.put(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;gong chen bo&quot;</span>);</span><br><span class="line">      hashOs.increment(<span class="string">&quot;age&quot;</span>, <span class="number">1</span>);</span><br><span class="line">      System.out.println(hashOs.keys());</span><br><span class="line">      System.out.println(hashOs.values());</span><br><span class="line">      System.out.println(hashOs.entries());</span><br><span class="line">&#125;     </span><br></pre></td></tr></table></figure>



<h3 id="测试-Json序列化"><a href="#测试-Json序列化" class="headerlink" title="测试 Json序列化"></a>测试 Json序列化</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">testBeanAndHash</span><span class="params">()</span> &#123;</span><br><span class="line">     <span class="type">User</span> <span class="variable">songyangJi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">12345L</span>, <span class="string">&quot;SongyangJi&quot;</span>, <span class="number">18</span>, <span class="number">73.5</span>, <span class="number">0</span>, <span class="literal">null</span>);</span><br><span class="line">     <span class="keyword">final</span> <span class="type">String</span> <span class="variable">user_json_key</span> <span class="operator">=</span> <span class="string">&quot;user_json&quot;</span>;</span><br><span class="line"></span><br><span class="line">     System.out.println(<span class="string">&quot;------- 使用 Json 存储对象 -------&quot;</span>);</span><br><span class="line">     redisTemplate.opsForValue().set(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId(), JsonUtil.stringfy(songyangJi));</span><br><span class="line">     <span class="type">User</span> <span class="variable">u</span> <span class="operator">=</span> JsonUtil.parse((String) redisTemplate.opsForValue().get(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()), User.class);</span><br><span class="line">     System.out.println(u);</span><br><span class="line">     u.setName(<span class="string">&quot;gong chen bo&quot;</span>);</span><br><span class="line">     <span class="type">BoundValueOperations</span> <span class="variable">valueOps</span> <span class="operator">=</span> redisTemplate.boundValueOps(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId());</span><br><span class="line">     valueOps.set(JsonUtil.stringfy(u));</span><br><span class="line">     System.out.println(redisTemplate.opsForValue().get(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()));</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<h3 id="测试-HyperLogLog"><a href="#测试-HyperLogLog" class="headerlink" title="测试 HyperLogLog"></a>测试 HyperLogLog</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">void</span> <span class="title function_">testHyperLogLog</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 使用HyperLogLog统计每天登录的用户量</span></span><br><span class="line">        <span class="keyword">final</span> <span class="type">long</span> <span class="variable">userId</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>().nextLong();</span><br><span class="line"><span class="comment">//        final long userId = 1L;</span></span><br><span class="line">        <span class="type">HyperLogLogOperations</span> <span class="variable">hyperLogLog</span> <span class="operator">=</span> redisTemplate.opsForHyperLogLog();</span><br><span class="line">        <span class="type">String</span> <span class="variable">key</span> <span class="operator">=</span> <span class="string">&quot;user:login:number:&quot;</span> + LocalDate.now();</span><br><span class="line">        hyperLogLog.add(key, userId);</span><br><span class="line">        System.out.println(hyperLogLog.size(key));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



<h3 id="测试-BitMap"><a href="#测试-BitMap" class="headerlink" title="测试 BitMap"></a>测试 BitMap</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">testBitMap</span><span class="params">()</span> &#123;</span><br><span class="line">  </span><br><span class="line">     <span class="comment">// 示例：使用BitMap记录用户本周是否有签到</span></span><br><span class="line">     <span class="keyword">final</span> <span class="type">long</span> <span class="variable">userId</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>().nextLong();</span><br><span class="line">     <span class="comment">// final long userId = 1L;</span></span><br><span class="line">     <span class="comment">// userId高48位用于将用户划分到不同的key，低16位作为位图偏移参数offset;</span></span><br><span class="line">     <span class="type">String</span> <span class="variable">keySign</span> <span class="operator">=</span> <span class="string">&quot;user:sign:&quot;</span> + LocalDate.now().getDayOfWeek() + <span class="string">&quot;:&quot;</span> + (userId &gt;&gt; <span class="number">16</span>);</span><br><span class="line">     <span class="comment">// offset参数必须大于或等于0，小于2^32(bit 映射被限制在 512 MB 之内)</span></span><br><span class="line">     redisTemplate.opsForValue().setBit(keySign, userId &amp; <span class="number">0xffff</span>, <span class="literal">true</span>);</span><br><span class="line">     System.out.println(<span class="string">&quot;是否签到：&quot;</span> + redisTemplate.opsForValue().getBit(keySign, userId &amp; <span class="number">0xffff</span>));</span><br><span class="line">     System.out.println(<span class="string">&quot;是否签到：&quot;</span> + redisTemplate.opsForValue().getBit(keySign, (userId + <span class="number">1</span>) &amp; <span class="number">0xffff</span>));</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<h3 id="测试-Lua"><a href="#测试-Lua" class="headerlink" title="测试 Lua"></a>测试 Lua</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">testLua</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">User</span> <span class="variable">songyangJi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">12345L</span>, <span class="string">&quot;SongyangJi&quot;</span>, <span class="number">18</span>, <span class="number">73.5</span>, <span class="number">0</span>, LocalDate.now().minusDays(<span class="number">1</span>));</span><br><span class="line">    <span class="keyword">final</span> <span class="type">String</span> <span class="variable">user_hash_key</span> <span class="operator">=</span> <span class="string">&quot;user&quot;</span>;</span><br><span class="line">    <span class="comment">// 使用Hash结构，map传入</span></span><br><span class="line">    redisTemplate.opsForHash().putAll(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId(), BeanAndMapConvertUtil.beanToMap(songyangJi));</span><br><span class="line">    System.out.println(redisTemplate.opsForHash().entries(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 构造 lua脚本</span></span><br><span class="line">    DefaultRedisScript&lt;String&gt; script = <span class="keyword">new</span> <span class="title class_">DefaultRedisScript</span>&lt;&gt;();</span><br><span class="line">    script.setLocation(<span class="keyword">new</span> <span class="title class_">ClassPathResource</span>(<span class="string">&quot;lua-script/user-sign.lua&quot;</span>)); <span class="comment">// 设置脚本所在位置，也可以直接把脚本内容放在字符串里</span></span><br><span class="line">    script.setResultType(String.class); <span class="comment">// 必须设置返回值类型（否则 execute 返回值为 null ）</span></span><br><span class="line"></span><br><span class="line">    List&lt;String&gt; keys = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">    keys.add(String.valueOf(songyangJi.getUserId()));</span><br><span class="line">    keys.add(LocalDate.now().toString());</span><br><span class="line"></span><br><span class="line">    System.out.println(<span class="string">&quot;签到成功与否：&quot;</span>+redisTemplate.execute(script, keys));</span><br><span class="line">    System.out.println(<span class="string">&quot;签到成功与否：&quot;</span>+redisTemplate.execute(script, keys));</span><br><span class="line">    System.out.println(redisTemplate.opsForHash().entries(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>resources&#x2F;lua-script&#x2F;user-sign.lua</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> score = redis.call(<span class="string">&#x27;hget&#x27;</span>, <span class="string">&#x27;user:&#x27;</span> .. KEYS[<span class="number">1</span>], <span class="string">&#x27;score&#x27;</span>)</span><br><span class="line"><span class="keyword">local</span> day = redis.call(<span class="string">&#x27;hget&#x27;</span>, <span class="string">&#x27;user:&#x27;</span> .. KEYS[<span class="number">1</span>], <span class="string">&#x27;lastSignDay&#x27;</span>)</span><br><span class="line"><span class="keyword">if</span> (day == KEYS[<span class="number">2</span>]) <span class="keyword">then</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;0&#x27;</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    redis.call(<span class="string">&#x27;hset&#x27;</span>, <span class="string">&#x27;user:&#x27;</span> .. KEYS[<span class="number">1</span>], <span class="string">&#x27;score&#x27;</span>, score + <span class="number">1</span>, <span class="string">&#x27;lastSignDay&#x27;</span>, KEYS[<span class="number">2</span>])</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;1&#x27;</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 在 lua 中数组的索引从 1 开始</span></span><br></pre></td></tr></table></figure>







<blockquote>
<p> 附录</p>
</blockquote>
<p>Code:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">LearnRedisSpringbootApplicationTests</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    RedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">flushDB</span><span class="params">()</span> &#123;</span><br><span class="line">        Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection().flushAll();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">testString</span><span class="params">()</span> &#123;</span><br><span class="line">        flushDB();</span><br><span class="line">        redisTemplate.opsForValue().set(<span class="string">&quot;str_key&quot;</span>, <span class="string">&quot;hello_world&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">testBeanAndHash</span><span class="params">()</span> &#123;</span><br><span class="line">        flushDB();</span><br><span class="line"></span><br><span class="line">        <span class="type">User</span> <span class="variable">songyangJi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">12345L</span>, <span class="string">&quot;SongyangJi&quot;</span>, <span class="number">18</span>, <span class="number">73.5</span>, <span class="number">0</span>, <span class="literal">null</span>);</span><br><span class="line">        <span class="keyword">final</span> <span class="type">String</span> <span class="variable">user_hash_key</span> <span class="operator">=</span> <span class="string">&quot;user_hash&quot;</span>;</span><br><span class="line">        <span class="keyword">final</span> <span class="type">String</span> <span class="variable">user_json_key</span> <span class="operator">=</span> <span class="string">&quot;user_json&quot;</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------ 使用 Hash 存储对象 ------&quot;</span>);</span><br><span class="line">        <span class="comment">// 使用Hash结构，map传入</span></span><br><span class="line">        redisTemplate.opsForHash().putAll(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId(), BeanAndMapConvertUtil.beanToMap(songyangJi));</span><br><span class="line"></span><br><span class="line">        <span class="type">BoundHashOperations</span> <span class="variable">hashOs</span> <span class="operator">=</span> redisTemplate.boundHashOps(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId());</span><br><span class="line">        System.out.println(hashOs.get(<span class="string">&quot;userId&quot;</span>));</span><br><span class="line">        System.out.println(hashOs.get(<span class="string">&quot;name&quot;</span>));</span><br><span class="line">        hashOs.put(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;gong chen bo&quot;</span>);</span><br><span class="line">        hashOs.increment(<span class="string">&quot;age&quot;</span>, <span class="number">1</span>);</span><br><span class="line">        System.out.println(hashOs.keys());</span><br><span class="line">        System.out.println(hashOs.values());</span><br><span class="line">        System.out.println(hashOs.entries());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------- 使用 Json 存储对象 -------&quot;</span>);</span><br><span class="line">        redisTemplate.opsForValue().set(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId(), JsonUtil.stringfy(songyangJi));</span><br><span class="line">        <span class="type">User</span> <span class="variable">u</span> <span class="operator">=</span> JsonUtil.parse((String) redisTemplate.opsForValue().get(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()), User.class);</span><br><span class="line">        System.out.println(u);</span><br><span class="line">        u.setName(<span class="string">&quot;gong chen bo&quot;</span>);</span><br><span class="line">        <span class="type">BoundValueOperations</span> <span class="variable">valueOps</span> <span class="operator">=</span> redisTemplate.boundValueOps(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId());</span><br><span class="line">        valueOps.set(JsonUtil.stringfy(u));</span><br><span class="line">        System.out.println(redisTemplate.opsForValue().get(user_json_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">testBitMap</span><span class="params">()</span> &#123;</span><br><span class="line">        flushDB();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 示例：使用BitMap记录用户本周是否有签到</span></span><br><span class="line">        <span class="keyword">final</span> <span class="type">long</span> <span class="variable">userId</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>().nextLong();</span><br><span class="line">        <span class="comment">// final long userId = 1L;</span></span><br><span class="line">        <span class="comment">// userId高48位用于将用户划分到不同的key，低16位作为位图偏移参数offset;</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">keySign</span> <span class="operator">=</span> <span class="string">&quot;user:sign:&quot;</span> + LocalDate.now().getDayOfWeek() + <span class="string">&quot;:&quot;</span> + (userId &gt;&gt; <span class="number">16</span>);</span><br><span class="line">        <span class="comment">// offset参数必须大于或等于0，小于2^32(bit 映射被限制在 512 MB 之内)</span></span><br><span class="line">        redisTemplate.opsForValue().setBit(keySign, userId &amp; <span class="number">0xffff</span>, <span class="literal">true</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;是否签到：&quot;</span> + redisTemplate.opsForValue().getBit(keySign, userId &amp; <span class="number">0xffff</span>));</span><br><span class="line">        System.out.println(<span class="string">&quot;是否签到：&quot;</span> + redisTemplate.opsForValue().getBit(keySign, (userId + <span class="number">1</span>) &amp; <span class="number">0xffff</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">testHyperLogLog</span><span class="params">()</span> &#123;</span><br><span class="line">        flushDB();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 使用HyperLogLog统计每天登录的用户量</span></span><br><span class="line">        <span class="keyword">final</span> <span class="type">long</span> <span class="variable">userId</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>().nextLong();</span><br><span class="line"><span class="comment">//        final long userId = 1L;</span></span><br><span class="line">        <span class="type">HyperLogLogOperations</span> <span class="variable">hyperLogLog</span> <span class="operator">=</span> redisTemplate.opsForHyperLogLog();</span><br><span class="line">        <span class="type">String</span> <span class="variable">key</span> <span class="operator">=</span> <span class="string">&quot;user:login:number:&quot;</span> + LocalDate.now();</span><br><span class="line">        hyperLogLog.add(key, userId);</span><br><span class="line">        System.out.println(hyperLogLog.size(key));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">testLua</span><span class="params">()</span> &#123;</span><br><span class="line">        flushDB();</span><br><span class="line"></span><br><span class="line">        <span class="type">User</span> <span class="variable">songyangJi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">12345L</span>, <span class="string">&quot;SongyangJi&quot;</span>, <span class="number">18</span>, <span class="number">73.5</span>, <span class="number">0</span>, LocalDate.now().minusDays(<span class="number">1</span>));</span><br><span class="line">        <span class="keyword">final</span> <span class="type">String</span> <span class="variable">user_hash_key</span> <span class="operator">=</span> <span class="string">&quot;user&quot;</span>;</span><br><span class="line">        <span class="comment">// 使用Hash结构，map传入</span></span><br><span class="line">        redisTemplate.opsForHash().putAll(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId(), BeanAndMapConvertUtil.beanToMap(songyangJi));</span><br><span class="line">        System.out.println(redisTemplate.opsForHash().entries(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 构造 lua脚本</span></span><br><span class="line">        DefaultRedisScript&lt;String&gt; script = <span class="keyword">new</span> <span class="title class_">DefaultRedisScript</span>&lt;&gt;();</span><br><span class="line">        script.setLocation(<span class="keyword">new</span> <span class="title class_">ClassPathResource</span>(<span class="string">&quot;lua-script/user-sign.lua&quot;</span>)); <span class="comment">// 设置脚本所在位置，也可以直接把脚本内容放在字符串里</span></span><br><span class="line">        script.setResultType(String.class); <span class="comment">// 必须设置返回值类型（否则 execute 返回值为 null ）</span></span><br><span class="line"></span><br><span class="line">        List&lt;String&gt; keys = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        keys.add(String.valueOf(songyangJi.getUserId()));</span><br><span class="line">        keys.add(LocalDate.now().toString());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;签到成功与否：&quot;</span>+redisTemplate.execute(script, keys));</span><br><span class="line">        System.out.println(<span class="string">&quot;签到成功与否：&quot;</span>+redisTemplate.execute(script, keys));</span><br><span class="line">        System.out.println(redisTemplate.opsForHash().entries(user_hash_key + <span class="string">&quot;:&quot;</span> + songyangJi.getUserId()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/NoSQL/" rel="tag"># NoSQL</a>
              <a href="/tags/Redis/" rel="tag"># Redis</a>
              <a href="/tags/SpringBoot-%E9%9B%86%E6%88%90%E4%B8%80%E5%88%87/" rel="tag"># SpringBoot 集成一切</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/09/25/%E5%8F%8D%E5%B0%84%E7%9A%84%E5%9F%BA%E7%A1%80%E3%80%81Class%E3%80%81Field%E3%80%81Method%E3%80%81Constructor%E7%B1%BB/" rel="prev" title="反射的基础、Class、Field、Method、Constructor类">
                  <i class="fa fa-chevron-left"></i> 反射的基础、Class、Field、Method、Constructor类
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/10/02/%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F%E3%80%81Java%E4%B8%AD%E7%9A%84%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E3%80%81Proxy%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E3%80%81%E5%AE%9E%E4%BE%8B%E5%88%86%E6%9E%90/" rel="next" title="代理模式、Java中的动态代理、Proxy源码分析、实例分析">
                  代理模式、Java中的动态代理、Proxy源码分析、实例分析 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
